package _2025_3_16;

import java.nio.channels.InterruptibleChannel;

public class MyBlockingDeque {
    private int[]elem;
    public MyBlockingDeque(int space) {
        if(space<=0) {
            throw new RuntimeException();
        }
        else elem=new int[space];

    }
    private volatile int head=0;//头下标
    private volatile int tail=0;//尾下标
    private volatile int size=0;//数组有效个数

    public void put(int value) throws InterruptedException {
        if(size>= elem.length){
            //阻塞，使其等待 this当前这个
            synchronized (this){
                this.wait(1);
            }
        }
        elem[tail]=value;
        tail++;
        if(tail==elem.length){
            tail=0;
        }
        size++;
    }
    public synchronized Integer take(){
        if(size==0){
            return null;
        }
        Integer key=elem[head];
        head++;
        if(head==elem.length){
            head=0;
        }
        size--;
        //唤醒阻塞等待线程
        synchronized (this){
            this.notifyAll();
        }
        return key;
    }

}
